﻿using System;
using System.Data;
using Telerik.Web.UI;
using System.Text;

namespace EXAM.Admin.Page_Admin
{
    public partial class Users : System.Web.UI.Page
    {
        string sErr = "";
        string _db = "EXA";
        protected void Page_Load(object sender, EventArgs e)
        {
            //Button1.Attributes.Add("onclick", "return blockConfirm('Are you sure you want to postback?', event, 330, 100,'','Custom title');");
            if (!IsPostBack)
            {
                LoadGroupCbo();
            }
        }

        private void LoadGroupCbo()
        {
            BUS.POGControl ctr = new BUS.POGControl();
            DataTable dt = ctr.GetAll(ref sErr);
            DataRow newRow = dt.NewRow();
            newRow["ROLE_ID"] = "";
            dt.Rows.InsertAt(newRow, 0);
            cboPOG.DataSource = dt;
            cboPOG.DataTextField = "ROLE_ID";
            cboPOG.DataValueField = "ROLE_ID";
            cboPOG.DataBind();
        }

        private void LoadAnal(RadComboBox cbo, string cate)
        {
            BUS.SSRFANVControl ctr = new BUS.SSRFANVControl();
            DataTable dt = ctr.GetCategory_SSRFANV(_db, cate, ref sErr);
            cbo.DataSource = dt;
            cbo.DataTextField = "Code";
            cbo.DataValueField = "Code";
            cbo.DataBind();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            RefreshForm("");
        }

        private void RefreshForm(string val)
        {
            txtID.Text = val;
            txtBirthplace.Text = val;
            txtComment.Text = val;
            txtEmail.Text = val;
            txtFirstName.Text = val;
            txtLastName.Text = val;
            txtUserName.Text = val;
            dpRegDate.SelectedDate = null;
            dpBirthday.SelectedDate = null;
            lbErr.Text = val;
            ckbANAL_U9.Checked = false;
            cboANAL_Q0.Text = val;
            cboANAL_U0.Text = val;
            cboANAL_U1.Text = val;
            txtANAL_U3.Text = val;
            txtANAL_U8.Text = "";
            cboPOG.SelectedValue = "";
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DTO.UserInfo usrInf = new DTO.UserInfo();
            usrInf = GetDataFromForm(usrInf);
            BUS.UserControl ctr = new BUS.UserControl();
            
            if (txtID.Text != "" && txtID.Text != "-1")
            {
                sErr = ctr.Update_User(usrInf);
                if (sErr != "")
                    lbErr.Text = sErr;
                else lbErr.Text = "Update successful";
            }
            else
            {
                DTO.UserInfo uinf = ctr.Get_User_ByUsername(usrInf.Username, ref sErr);
                if (uinf.Username == "")
                {
                    usrInf.Password = Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes("")));
                    txtID.Text = ctr.Add_User(usrInf, ref sErr).ToString();
                    txtPass.Text = usrInf.Password;
                    if (sErr != "")
                        lbErr.Text = sErr;
                    else lbErr.Text = "Insert successful";
                }
                else lbErr.Text = "User is exist";
            }
            if (sErr == "")
                dgvList.Rebind();
        }

        private DTO.UserInfo GetDataFromForm(DTO.UserInfo usrInf)
        {
            if (txtID.Text != "" && txtID.Text != "-1")
                usrInf.ID = Convert.ToInt64(txtID.Text);
            usrInf.Birthdate = BUS.CommonControl.ConvertDateToInt(dpBirthday.SelectedDate);
            usrInf.Birthplace = txtBirthplace.Text;
            usrInf.Email = txtEmail.Text;
            usrInf.Firstname = txtFirstName.Text;
            usrInf.Lastname = txtLastName.Text;

            usrInf.Regdate = BUS.CommonControl.ConvertDateToInt(dpRegDate.SelectedDate);
            usrInf.Ssn = txtComment.Text;
            usrInf.Username = txtUserName.Text;
            usrInf.Password = txtPass.Text;
            usrInf.Ip = txtIP.Text;
            usrInf.ANAL_U9 = ckbANAL_U9.Checked ? "True" : "False";
            usrInf.ANAL_U0 = cboANAL_U0.Text;
            usrInf.ANAL_U1 = cboANAL_U1.Text;
            usrInf.ANAL_U2 = cboANAL_Q0.Text;
            usrInf.ANAL_U3 = txtANAL_U3.Text;
            usrInf.ANAL_U8 = txtANAL_U8.Text;
            usrInf.GroupCode = cboPOG.SelectedValue;
            return usrInf;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridItem item in dgvList.SelectedItems)
            {
                if (item.ItemIndex >= 0)
                {
                    string id = item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"].ToString();
                    BUS.UserControl ctr = new BUS.UserControl();
                    sErr = ctr.Delete_User(Convert.ToInt64(id));
                }
            }
            dgvList.Rebind();
        }


        protected void dgvList_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName.ToUpper() == "SELECTED")
            {
                string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
                BUS.UserControl ctr = new BUS.UserControl();
                SetDataToForm(ctr.Get_User(Convert.ToInt64(id), ref sErr));
                lbErr.Text = "";

            }
            else if (e.CommandName.ToUpper() == "RESET")
            {
                string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
                BUS.UserControl ctr = new BUS.UserControl();
                DTO.UserInfo inf = ctr.Get_User(Convert.ToInt64(id), ref sErr);
                inf.Password = Convert.ToBase64String(new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes("")));
                sErr = ctr.Update_User(inf);
                if (sErr != "")
                    lbErr.Text = sErr;
                else
                    lbErr.Text = inf.Username + "has just been reset password!";
            }
        }

        private void SetDataToForm(DTO.UserInfo usrInf)
        {
            if (usrInf.ID != -1)
                txtID.Text = usrInf.ID.ToString();
            txtUserName.Text = usrInf.Username;
            txtEmail.Text = usrInf.Email;
            txtFirstName.Text = usrInf.Firstname;
            txtBirthplace.Text = usrInf.Birthplace;
            txtComment.Text = usrInf.Ssn;
            txtLastName.Text = usrInf.Lastname;
            dpBirthday.SelectedDate = BUS.CommonControl.ConvertIntToDate(usrInf.Birthdate);
            dpRegDate.SelectedDate = BUS.CommonControl.ConvertIntToDate(usrInf.Regdate);
            txtIP.Text = usrInf.Ip;
            txtPass.Text = usrInf.Password;
            ckbANAL_U9.Checked = usrInf.ANAL_U9 == "True";
            cboANAL_U0.Text = usrInf.ANAL_U0;
            cboANAL_U1.Text = usrInf.ANAL_U1;
            cboANAL_Q0.Text = usrInf.ANAL_U2;
            txtANAL_U3.Text = usrInf.ANAL_U3;
            txtANAL_U8.Text = usrInf.ANAL_U8;
            cboPOG.SelectedValue = usrInf.GroupCode;
        }

        protected void dgvList_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            BUS.UserControl ctr = new BUS.UserControl();
            dgvList.DataSource = ctr.GetAll_User(ref sErr);
        }

        protected void cboANAL_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadAnal((RadComboBox)sender, ((RadComboBox)sender).ID.Replace("cboANAL_", ""));
        }

        protected void PostbackButton1_Click(object sender, EventArgs e)
        {

        }

        protected void txtUserName_TextChanged(object sender, EventArgs e)
        {
            BUS.UserControl ctr = new BUS.UserControl();
            DTO.UserInfo uinf = ctr.Get_User_ByUsername(txtUserName.Text, ref sErr);
            if (uinf.Username != "")
                lbErr.Text = "User is exist";
        }
    }
}
